package com.fdq.dianping.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.fdq.dianping.entity.Result;
import com.fdq.dianping.entity.SeckillVoucher;
import com.fdq.dianping.entity.Voucher;
import com.fdq.dianping.mapper.VoucherMapper;
import com.fdq.dianping.service.ISeckillVoucherService;
import com.fdq.dianping.service.IVoucherService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author fdq
 * @since 2024-12-29
 */
@Service
public class VoucherServiceImpl extends ServiceImpl<VoucherMapper, Voucher> implements IVoucherService {
    @Resource
    private ISeckillVoucherService seckillVoucherService;
    @Override
    @Transactional      //保证保存优惠券和秒杀券都成功
    public Result addSeckillVoucher(Voucher voucher) {
        //保存优惠券，秒杀券同时也是优惠券
        save(voucher);
        //保存秒杀券
        SeckillVoucher seckillVoucher = new SeckillVoucher();
        seckillVoucher.setVoucherId(voucher.getId());
        seckillVoucher.setStock(voucher.getStock());
        seckillVoucher.setBeginTime(voucher.getBeginTime());
        seckillVoucher.setEndTime(voucher.getEndTime());
        boolean save = seckillVoucherService.save(seckillVoucher);
        if(save){
            return Result.success();
        }else {
            return Result.error("添加优惠券失败");
        }

    }

    @Override
    public Result addNormalVoucher(Voucher voucher) {
        boolean save = save(voucher);
        if(save){
            return Result.success();
        }else {
            return Result.error("添加优惠券失败");
        }
    }

    @Override
    public Result deleteNormalVoucher(Long id) {
        boolean removed = removeById(id);
        if(removed){
            return Result.success();
        }else {
            return Result.error("删除失败");
        }
    }

    @Override
    @Transactional
    public Result deleteSeckillVoucher(Long id) {
        boolean voucherRemove = removeById(id);
        boolean seckillRemove = seckillVoucherService.removeById(id);
        if(voucherRemove && seckillRemove){
            return Result.success();
        }else {
            return Result.error("删除秒杀优惠券失败");
        }
    }

    @Override
    public Result updateSeckillById(Voucher voucher) {
        boolean voucherUpdate = updateById(voucher);
        SeckillVoucher seckillVoucher = new SeckillVoucher();
        BeanUtil.copyProperties(voucher,seckillVoucher,true);
        seckillVoucher.setVoucherId(voucher.getId());
        System.out.println(seckillVoucher);
        boolean seckillUpdate = seckillVoucherService.updateById(seckillVoucher);
        if(voucherUpdate && seckillUpdate){
            return Result.success();
        }else {
            return Result.error("更新秒杀优惠券失败");
        }
    }

}
